package cn.xqapp.core;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;

import java.util.function.Supplier;

public class BaseClient implements Runnable{

    protected String host;
    protected int port;
    protected Supplier<ChannelHandler> channelHandlerSupplier;

    public BaseClient(String host, int port, Supplier<ChannelHandler> channelHandlerSupplier){
        this.host = host;
        this.port = port;
        this.channelHandlerSupplier = channelHandlerSupplier;
    }

    @Override
    public void run() {
        EventLoopGroup workerGroup = new NioEventLoopGroup();
        try {
            Bootstrap b = new Bootstrap();
            b.group(workerGroup)
                    .channel(NioSocketChannel.class)
                    .option(ChannelOption.SO_KEEPALIVE, true)
                    .handler(channelHandlerSupplier.get());

            ChannelFuture f = b.connect(this.host, this.port).sync();
            f.channel().closeFuture().sync();
        }catch(Exception ex){
            System.out.println(ex.getMessage());
        }finally {
            workerGroup.shutdownGracefully();
        }
    }
}
